<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/16 0016
 * Time: 上午 11:17
 */
namespace app\admin\model;
use think\Db;
use think\Model;

class Lesson extends Model {
    public static function getbyfilter( $f = [] )
    {
        if ( isset( $f[ 'pid' ] ) && $f[ 'pid' ] !== '' && $f[ 'pid' ] != 0 ) {
            $pid = is_array( $f['pid'] ) ? $f['pid'] : explode( ',' , $f[ 'pid' ] );
            $db  = Db::name( 'lesson' )->field( 'id,title,cover,cover_desc,slider,is_recommend,pid' )->where( [ 'is_deleted' => 1 , 'status' => 1 , 'type' => 12 ] )->order( 'sort asc,id asc' );
            ( isset( $f[ 'keywords' ] ) && $f[ 'keywords' ] !== '' ) && $db->whereLike( 'keywords' , "%{$f['keywords']}%" );
            foreach ( $pid as $v ) {
                if( $v !== '' && $v != 0 ){
                    $db->where( "FIND_IN_SET({$v},pid)" );
                }
            }
            return $db;
        } else {
            return Db::name( 'lesson' )->field( 'id,title,cover,cover_desc,slider,is_recommend' )->where( [ 'is_deleted' => 1 , 'status' => 1 , 'type' => 12 ] )->order( 'sort asc,id asc' );
        }
    }

    /**
     * 获取相关信息
     * @param $cate_ids
     * @param $type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getLessonAttr( $cate_ids  , $type = 'time' )
    {
        if (empty($cate_ids)) {
            return "";
        }
        $cate_ids = explode(',', $cate_ids);
        $select   = Db::name('lesson_cate')->field('id,name,pid')->where('id', 'in', $cate_ids)->select();
        foreach ( $select as $sk => $sv ) {
            $select[$sk]['parent']   = Db::name('lesson_cate')->field('id,name')->where([ 'id' => $sv['pid'] ] )->find();
        }
        foreach ( $select as $k => $v ){
            if( isset( $v['parent']['name'] ) && !empty( $v['parent']['name'] ) ){
                if( $type == 'time' ){
                    if( strpos( $v['name'] , '天' ) !== false ){
                        return $v['name'];
                    }
                }else{
                    if( strpos( $v['parent']['name'] , '年级' ) !== false ){
                        $nianji[] = $v;
                    }
                }
            }
        }
        if( !empty( $nianji ) ){
            $zongCate = Db::name('lesson_cate')->field('id,name,pid')->where('pid' , $nianji[0]['parent']['id'] )->select();
            foreach ( $zongCate as $k => $v ){
                foreach ( $nianji as $key => $val ){
                    if( $v['id'] == $val['id'] ){
                        $zongCate[$k]['is_true'] = true;
                        continue;
                    }
                }
            }
        }
        return $type=='time' ? "" : $zongCate;
    }
}